package api.service;

import api.model.ApiAuthInter;
import api.model.ApiColumn;
import api.model.ApiTable;
import m.common.model.type.FieldType;
import m.common.model.util.ModelCheckUtil;
import m.common.model.util.ModelUpdateUtil;
import m.common.service.Service;
import m.system.cache.CacheUtil;
import m.system.db.TransactionManager;
import m.system.exception.MException;
import m.system.util.*;
import manage.model.StatusModel;

import java.util.ArrayList;
import java.util.List;

public class ApiAuthInterService extends Service {
    public String save(ApiAuthInter model) throws Exception {
        String msg;
        TransactionManager tm=new TransactionManager();
        try {
            tm.begin(model.getOid());
            ModelCheckUtil.checkNotNull(model, "name","modelTable.oid");
            if(!model.getName().matches("[a-z_0-9]*")) throw new MException(this.getClass(),"字段只能包含小写字母数字和下划线");
            ModelCheckUtil.checkUniqueCombine(model,new String[]{"name","auth.oid"},"接口名称已存在");
            if(StringUtil.isSpace(model.getOid())){
                model.setOid(GenerateID.generatePrimaryKey());
                model.setStatus(StatusModel.Status_Disabled);
                ModelUpdateUtil.insertModel(model);
                msg="保存成功";
            }else{
                ModelUpdateUtil.updateModel(model, "description","name","modelTable.oid","subTables","type","dataHandler");
                msg="修改成功";
            }
            CacheUtil.clear(ApiAuthInter.class);
            tm.commit();
        }catch (Exception e){
            tm.rollback();
            throw e;
        }
        return msg;
    }
    /**
     * 获取接口信息
     */
    public ApiAuthInter get(String authId,String name){
        return CacheUtil.get(ApiAuthInter.class,authId,name);
    }

    public JSONMessage getParamExample(String authId,String name){
        ApiAuthInter ai= get(authId,name);
        if(ai.getType().equals("A")){
            return toImportExample(ai);
        }else{
            return toQueryExample(ai);
        }
    }
    public JSONMessage toImportExample(ApiAuthInter ai){
        ApiTable apiTable=CacheUtil.get(ApiTable.class,ai.getModelTable().getOid());
        List<ApiColumn> cols=CacheUtil.getList(ApiColumn.class,apiTable.getOid());
        JSONMessage model=new JSONMessage();
        JSONMessage method=new JSONMessage();
        method.push("title",ai.getName());
        method.push("description",ai.getDescription());
        method.push("authId",ai.getAuth().getAuthId());
        method.push("path","/api/inter/"+ai.getName());
        List<JSONMessage> apiParams=new ArrayList<>();
        method.push("params",apiParams);
        for(ApiColumn col : cols){
            if(col.getIsinit().equals("Y")){
                if(ObjectUtil.notEmptyOid(col.getModelTable())){
                    model.push(col.getName(),new JSONMessage().push("oid",col.getDescription()+"主键"));
                    apiParams.add(new JSONMessage().push("name","model."+col.getName()+".oid").push("description",col.getDescription()+"主键")
                        .push("type","STRING").push("length","50").push("notnull","Y".equals(col.getNotnull())).push("tableOid",col.getModelTable().getOid()));
                }else{
                    model.push(col.getName(),col.getDescription()+"，"+(col.getNotnull().equals("Y")?"非空，":"")+col.getType());
                    apiParams.add(new JSONMessage().push("name","model."+col.getName()).push("description",col.getDescription())
                        .push("dictType",col.getDictType()).push("dictOption",col.getDictOption())
                        .push("type",col.getType()).push("length",col.getLength()).push("notnull","Y".equals(col.getNotnull())));
                }
            }
        }
        return new JSONMessage()
            .push("request",new JSONMessage()
                .push("model",model))
            .push("response",new JSONMessage()
                .push("code","0:正常，其他错误，INT")
                .push("model",model)
                .push("msg","返回消息"))
            .push("method",method);
    }
    public JSONMessage toQueryExample(ApiAuthInter ai){
        ApiTable apiTable=CacheUtil.get(ApiTable.class,ai.getModelTable().getOid());
        List<ApiColumn> cols=CacheUtil.getList(ApiColumn.class,apiTable.getOid());
        JSONMessage params=new JSONMessage();
        JSONMessage model=new JSONMessage();
        JSONMessage method=new JSONMessage();
        method.push("title",ai.getName());
        method.push("description",ai.getDescription());
        method.push("authId",ai.getAuth().getAuthId());
        method.push("path","/api/inter/"+ai.getName());
        List<JSONMessage> apiParams=new ArrayList<>();
        method.push("params",apiParams);
        StringBuilder sortField=new StringBuilder();
        for(ApiColumn col : cols){
            if(col.getIsinit().equals("Y")){
                if(ObjectUtil.notEmptyOid(col.getModelTable())){
                    sortField.append(",").append(col.getName()).append(".oid:").append(col.getDescription());
                    ApiTable at=CacheUtil.get(ApiTable.class,col.getModelTable().getOid());
                    params.push(col.getName()+".oid",at.getDescription()+"主键");
                    apiParams.add(new JSONMessage().push("name","params["+col.getName()+".oid]").push("description",col.getDescription()+"主键")
                        .push("type","STRING").push("length","50").push("tableOid",col.getModelTable().getOid()));
                    if(ArrayUtil.isContain(ai.getSubTables(),col.getField())){
                        JSONMessage m=new JSONMessage();
                        List<ApiColumn> clist=CacheUtil.getList(ApiColumn.class,col.getModelTable().getOid());
                        for(ApiColumn c : clist){
                            if(ObjectUtil.notEmptyOid(c.getModelTable())){
                                m.push(c.getName(),new JSONMessage().push("oid",c.getDescription()+"主键"));
                            }else if(c.getName().equals("oid")) {
                                m.push(c.getName(), at.getDescription() + "主键");
                            }else{
                                m.push(c.getName(),c.getDescription()+"，"+(c.getNotnull().equals("Y")?"非空，":"")+c.getType());
                            }
                        }
                        model.push(col.getName(),m);
                    }else {
                        model.push(col.getName(), new JSONMessage().push("oid", at.getDescription() + "主键"));
                    }
                }else{
                    sortField.append(",").append(col.getName()).append(":").append(col.getDescription());
                    if(FieldType.INT.toString().equals(col.getType())
                        ||FieldType.DOUBLE.toString().equals(col.getType())
                        ||FieldType.DATE.toString().equals(col.getType())){
                        params.push(col.getName()+"_down",col.getDescription()+" 下限，"+col.getType());
                        apiParams.add(new JSONMessage().push("name","params["+col.getName()+"_down]").push("description",col.getDescription()+" 下限")
                            .push("type",col.getType()).push("length",col.getLength()));
                        params.push(col.getName()+"_up",col.getDescription()+" 上限，"+col.getType());
                        apiParams.add(new JSONMessage().push("name","params["+col.getName()+"_up]").push("description",col.getDescription()+" 上限")
                            .push("type",col.getType()).push("length",col.getLength()));
                    }else{
                        params.push(col.getName(),col.getDescription()+"，"+col.getType());
                        apiParams.add(new JSONMessage().push("name","params["+col.getName()+"]").push("description",col.getDescription())
                            .push("dictType",col.getDictType()).push("dictOption",col.getDictOption())
                            .push("type",col.getType()).push("length",col.getLength()));
                    }
                    model.push(col.getName(),col.getDescription()+"，"+(col.getNotnull().equals("Y")?"非空，":"")+col.getType());
                }
            }
        }
        apiParams.add(new JSONMessage().push("name","page.index").push("description","分页-起始位置").push("type","INT"));
        apiParams.add(new JSONMessage().push("name","page.num").push("description","分页-每页条数").push("type","INT"));
        apiParams.add(new JSONMessage().push("name","order.name").push("description","排序-字段").push("type","STRING").push("length","50").push("dictOption",sortField.substring(1)));
        apiParams.add(new JSONMessage().push("name","order.oper").push("description","排序-顺序").push("type","STRING").push("length","50").push("dictOption","asc:升序,desc:降序"));
        return new JSONMessage()
            .push("request",new JSONMessage()
                .push("page",new JSONMessage().push("index","开始位置 0").push("num","每页条数 10"))
                .push("order",new JSONMessage().push("name","排序字段").push("oper","排序规则 asc"))
                .push("params",params))
            .push("response",new JSONMessage()
                .push("code","0:正常，其他错误，INT")
                .push("list",new JSONMessage[]{model}))
            .push("method",method);
    }
}
